package com.sc.controller;

import com.github.pagehelper.PageInfo;
import com.sc.pojo.Class;
import com.sc.pojo.User;
import com.sc.service.ClassService;
import com.sc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/class")
public class ClassController {
    @Autowired
    UserService us;
    @Autowired
    ClassService cs;
    @RequestMapping("/show")
    public String show(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "4") Integer pageSize, String keyword, Map m) {
        PageInfo<Class> p = cs.show(pageNum, pageSize,keyword);
        m.put("p",p);
        m.put("keyword",keyword);
        List<User> list = us.queryByRoleid(2);
        m.put("teacherList",list);
        return "/admin/class/list";
    }

    @RequestMapping("/add")
    public String add(Class c) {
        if (c.getTid()==-1) c.setTid(null);
        cs.add(c);
        return "redirect:/class/show";
    }
    @RequestMapping("/upd")
    public String upd(Class after) {
        // 改变后的班级id 和老师id
        Integer cid = after.getId();
        Integer tid = after.getTid();
        // 改变前的班级id 和老师id
        Class before = cs.queryById(cid);
        Integer beforeCid = before.getId();
        Integer beforeTid = before.getTid();
        // 如果改变前有老师
        if (beforeTid != null) {
            //把前老师设为无班级状态
            User beforeUser = us.selectById(beforeTid);
            beforeUser.setClassid(null);
            us.upd(beforeUser);
        }
        //改为无老师状态
        if (tid == -1) {
            after.setTid(null);
        } else {
            //改为其他老师, 把该老师班级改为本班
            User afterUser = us.selectById(tid);
            afterUser.setClassid(cid);
            us.upd(afterUser);
            //如果新老师原先有班级，该班设为无老师状态
            Class c = cs.queryByTid(afterUser.getId());
            if (c != null) {
                c.setTid(null);
                cs.upd(c);
            }
        }
        //更新本班信息
        cs.upd(after);
        return "redirect:/class/show";
    }
    @RequestMapping("/del")
    public String del (Integer id) {
        cs.del(id);
        return "redirect:/class/show";
    }
    @RequestMapping("/delAll")
    public String delAll (Integer[] id) {
        if (id!=null) cs.delAll(id);
        return "redirect:/class/show";
    }
}
